import React, { useEffect, useMemo, useState } from "react";
import { Route, Switch, Redirect } from "react-router-dom";
import Home from "../views/sandbox/home/Home";
import UserList from "../views/sandbox/user-manage/UserList";
import RoleList from "../views/sandbox/right-manage/RoleList";
import RightList from "../views/sandbox/right-manage/RightList";
import NotFound from "../views/sandbox/NotFound";
import axios from "axios";
import { readToken } from "../util";
import NoPermission from "../views/sandbox/NoPermission";
import NewsAdd from "../views/sandbox/news-manage/NewsAdd";
import NewsDraft from "../views/sandbox/news-manage/NewsDraft";
import NewsPreview from "../views/sandbox/news-manage/NewsPreview";
import AuditList from "../views/sandbox/audit-manage/AuditList";
import Audit from "../views/sandbox/audit-manage/Audit";
/** @import { Right, ReactState } from "../types"; */

const routerMapping = {
    "/home": Home,
    "/user-manage/list": UserList,
    "/right-manage/role/list": RoleList,
    "/right-manage/right/list": RightList,
    "/news-manage/add": NewsAdd,
    "/news-manage/draft": NewsDraft,
    "/news-manage/preview/:id": NewsPreview,
    "/news-manage/update/:id": () => <NewsAdd type="update" />,
    "/audit-manage/list": AuditList,
    "/audit-manage/audit": Audit
};

export default function NewsRouter() {
    // 后端返回的权限列表
    /** @type {ReactState<Right[]>} */
    const [rights, setRights] = useState([]);
    const loggedInUser = useMemo(readToken, []);

    useEffect(() => {
        Promise.all([
            axios.get("/rights"),
            axios.get("/children"),
        ])
            .then((results) => {
                setRights([...results[0].data, ...results[1].data]);
            })
            .catch((errors) => console.log(errors));
    }, []);

    /** 判断当前登录用户是否拥有某个路径的权限
     * @type {(right: Right) => boolean} */
    const isLoggedInUserHasPermission = (right) =>
        // 该路径需要启用，
        // 且该路径需要登录用户的角色拥有
        (right.pagepermisson || right.routepermisson) && loggedInUser.role.rights.includes(right.key);

    return (
        <Switch>
            {rights.map((right) => {
                let component = routerMapping[right.key] ?? NotFound;
                if (!isLoggedInUserHasPermission(right))
                    component = NoPermission;
                return <Route
                    key={right.id}
                    path={right.key}
                    component={component}
                    exact
                />;
            })}

            {/* 重定向 / 到首页 */}
            <Redirect from="/" to="/home" exact />
            {/* 404 处理 */}
            {/* rights.length > 0 是为了避免路径还没请求完毕时显示 404 */}
            {rights.length > 0 && <Route path="*" component={NotFound} />}
        </Switch>
    );
}
